package com.misyi.designpattern.prototype;

import lombok.Data;
import org.openjdk.jol.vm.VM;

/**
 * 原型模式
 *
 * @author licong
 * @date 2021-09-12 下午7:40
 */
public class PrototypePatternDemo {

    public static void main(String[] args) {
        Product product = new Product();
        product.setName("测试产品名称");
        Component component = new Component();
        component.setName("测试组件名称");
        product.setComponent(component);

        // 进行拷贝
        Product clone = product.clone();
        System.out.println(clone);

        // 对比地址值
        System.out.println(VM.current().addressOf(product));
        System.out.println(VM.current().addressOf(clone));
        System.out.println(VM.current().addressOf(product.getComponent()));
        System.out.println(VM.current().addressOf(clone.getComponent()));

        // 拷贝分为浅拷贝和深拷贝
        // 浅拷贝: 仅仅只是拷贝了对象的引用, 不会创建一个新的对象
        // 深拷贝: 创建一个新的对象, 所有的引用都不相关联
    }



    @Data
    public static class Product {

        private String name;

        private Component component;

        @Override
        protected Product clone() {
            Product product = new Product();
            product.setName(this.getName());
            product.setComponent(this.getComponent().clone());
            return product;
        }
    }


    @Data
    private static class Component {
        private String name;

        @Override
        protected Component clone() {
            Component component = new Component();
            component.setName(name);
            return component;
        }
    }

}
